﻿using SIG.DAL.Dapper.Model;
using Dapper;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;

namespace SIG.DAL.Dapper.Repositories
{
    public class EmailRepository
    {
        private DbConnection _connection;

        public Email GetById(int id)
        {
            Email result;
            using (_connection = Utilities.GetOpenConnection())
            {
                result = _connection.Get<Email>(id);
            }
            return result;
        }
        public int? Create(Email model)
        {
            int? result;
            using (_connection = Utilities.GetOpenConnection())
            {
                result = _connection.Insert(model);
            }
            return result;
        }

        public int Update(Email model)
        {
            int result;
            using (_connection = Utilities.GetOpenConnection())
            {
                result = _connection.Update(model);
            }
            return result;
        }
        public int Delete(Email model)
        {
            int result;
            using (_connection = Utilities.GetOpenConnection())
            {
                result = _connection.Delete(model);
            }
            return result;
        }

        public int Delete(int id)
        {
            int result;
            using (_connection = Utilities.GetOpenConnection())
            {
                result = _connection.Delete<Email>(id);
            }
            return result;
        }

        public bool DeleteEmails(int[] Ids)
        {

            // string[] ids = Ids.Split(',');
            //long[] IdItems = Array.ConvertAll<string, long>(ids, long.Parse);  
            //List<Email> lEmails = _uow.Emails.GetAll().Where(e=>IdItems.Contains(e.Id)).ToList();
            try
            {
                using (_connection = Utilities.GetOpenConnection())
                {
                    foreach (int id in Ids)
                    {
                        var vEmail = _connection.Get<Email>(id);
                        if (vEmail != null)
                        {
                            vEmail.Active = false;
                            _connection.Update(vEmail);
                        }
                    }

                }

                return true;

            // _loggingService.Info(string.Format(Logs.BulkTrash, EntityNames.Email));
        }
            catch (Exception er)
            {
               // _loggingService.Error(er.Message, er);
                return false;
            }


}
        /// <summary>
        /// 彻底删除
        /// </summary>
        /// <param name="Ids"></param>
        /// <returns></returns>
        public bool RemoveEmails(int[] Ids)
        {

            try
            {

                using (_connection = Utilities.GetOpenConnection())
                    {
                        foreach (int id in Ids)
                        {
                    _connection.Delete<Email>(id);
                           
                        }

                    }
                return true;
            }
            catch (Exception er)
            {
                // _loggingService.Error(er.Message, er);
                return false;
            }


        }

        /// <summary>
        /// 还原邮件
        /// </summary>
        /// <param name="Ids"></param>
        /// <returns></returns>
        public bool RestoreEmails(int[] Ids)
        {
            try
            {
                using (_connection = Utilities.GetOpenConnection())
                {
                    foreach (int id in Ids)
                    {

                        Email vEmail = _connection.Get<Email>(id);
                        if (vEmail != null)
                        {
                            vEmail.Active = true;
                            _connection.Update(vEmail);
                        }
                    }
                  
                }

                return true;
            }
            catch (Exception er)
            {              
                return false;
            }

          
        }

        public IEnumerable<Email> GetActiveItems()
        {
            IEnumerable<Email> result;
            using (_connection = Utilities.GetOpenConnection())
            {
                result = _connection.GetList<Email>(new { Active = true });
            }
            return result;
        }



        public Email GetPrev(int id)
        {
            Email result;
            using (_connection = Utilities.GetOpenConnection())
            {
                result = _connection.GetList<Email>( "where Active = 1 and Id < @Id", new { Id = id })
                    .OrderByDescending(m=>m.Id).FirstOrDefault();
            }
            return result;
        }
        public Email GetNext(int id)
        {
            Email result;
            using (_connection = Utilities.GetOpenConnection())
            {
                result = _connection.GetList<Email>("where Active = 1 and Id > @Id", new { Id = id })
                    .OrderByDescending(m => m.Id).FirstOrDefault();
            }
            return result;
        }

        public IEnumerable<Email> GetListPagedAcitveItems(int pageIndex, int pageSize)
        {
            IEnumerable<Email> result;
            using (_connection = Utilities.GetOpenConnection())
            {               
                result = _connection.GetListPaged<Email>(pageIndex, pageSize, "where Active=1", "CreatedDate desc");
            }
            return result;
        }

        public IEnumerable<Email> GetListPagedAcitveItems(int pageIndex, int pageSize, out int totalCount)
        {
            IEnumerable<Email> result;
            using (_connection = Utilities.GetOpenConnection())
            {
                totalCount = _connection.RecordCount<Email>("where Active=1");
                result = _connection.GetListPaged<Email>(pageIndex, pageSize, "where Active=1", "CreatedDate desc");
            }
            return result;
        }
       
      
        public IEnumerable<Email> GetListPagedItems(int pageIndex, int pageSize, out int totalCount)
        {
            IEnumerable<Email> result;
            using (_connection = Utilities.GetOpenConnection())
            {
                totalCount = _connection.RecordCount<Email>();
                result = _connection.GetListPaged<Email>(pageIndex, pageSize, null, "CreatedDate desc");
            }
            return result;
        }

        public IEnumerable<Email> GetListPagedItems(int pageIndex, int pageSize, string keyword, bool active, out int totalCount)
        {
            IEnumerable<Email> result;
            using (_connection = Utilities.GetOpenConnection())
            {
                keyword = !string.IsNullOrEmpty(keyword) ? keyword.Replace("[", "[[]").Replace("%", "[%]") : keyword;
                string likeKeyword = "%" + keyword + "%";

                var sql = "where Active = @Active ";

                if (!string.IsNullOrEmpty(keyword))
                {
                    sql = sql + " and (Subject like @Keyword or Body like @Keyword)";
                }
             

                totalCount = _connection.RecordCount<Email>(sql,
                    new { Keyword = likeKeyword , Active = active });
                result = _connection.GetListPaged<Email>(pageIndex, pageSize, sql, "CreatedDate desc",
                    new { Keyword = likeKeyword, Active = active });
            }
            return result;
        }
    }

}
